import React from 'react';
import styles from "./index.css";
import "./index.css";
import { Button, Input, Layout, Progress, Message, Popover, Badge, Table, Card} from 'element-react';
import { articleReview, advise2Chinese } from '../../ai/api';
import moment from 'moment';


const { ipcRenderer } = require('electron');
var counterInterval = null;
const NEED_TRANSLATION = false;

class HistoryRecordsTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      columns: [
        {
          label: "提交时间",
          prop: "reviewTime",
          width: 160,
        },
        {
          label: "",
          prop: "zip",
          width: 80,
          render: (row, column, index)=>{
            return <Button size='small'>查看</Button>
          }
        }
      ]
    };
  }

  render() {
    return (
      <Table
        style={{width: 260}}
        columns={this.state.columns}
        data={this.props.recordList}
        border={true}
        height={500}
      />
    )
  }
}

class HistoryRecords extends React.Component {
  render() {
    const items = this.props.items;
    return (
      <Popover placement="top-start" width="400" trigger="hover" content={(<HistoryRecordsTable recordList={items}/>)}>
        <Badge value={ items.length } max={ 99 }>
          <Button>记录</Button>
        </Badge>
      </Popover>
    )
  }
}

class CustomWriteBoard extends React.Component {

  constructor(props) {
    super(props);
    let title = props.location.state? props.location.state.title: null;
    let introduction = props.location.state? props.location.state.introduction: null;

    if (!window.location.articleContent) {
      window.location.articleContent = {}
    }

    if (title) {
      window.location.lastArticleTitle = title;
      window.location.lastIntroduction = introduction;
    } else if(window.location.lastArticleTitle) {
      title = window.location.lastArticleTitle;
      introduction = window.location.lastIntroduction
    } else {
      title = '自由发挥写作';
      window.location.lastArticleTitle = '自由发挥写作';
      introduction = '';
      window.location.lastIntroduction = '';
    }

    const articleContent = window.location.articleContent[title]?window.location.articleContent[title]: '';

    this.state = {
      progress: 0,
      articleContent: articleContent,
      adviseChinese: '',
      adviseEnglish: '',
      advise: '',
      title: title,
      isEnglishAdvice: false,
      records:[],
      submitLoading: false,
      introduction: introduction,
    }

    this.readHistoryArticleRecords();
  }

  createWindow = () => {
    ipcRenderer.send('create-window');
  }

  createWNoBarWindow = () => {
    ipcRenderer.send('create-nobar-window');
  }

  createNoBarWindowWithButton = () => {
    ipcRenderer.send('create-nobar-window-button');
  }

  createWindowDrag = () => {
    ipcRenderer.send('create-nobar-window-drag');
  }

  createWindowTrans = () => {
    ipcRenderer.send('create-window-trans');
  }

  handleArticleChange = (e) => {
    this.setState({articleContent:e});
    window.location.articleContent[this.state.title] = e;
  };

  handleTitleChange = (e) => {
    this.setState({title:e});
  };

  submitComposition = () => {
    this.setState({progress: 0, submitLoading: true});
    if (counterInterval) {
      clearInterval(counterInterval);
    }
    counterInterval = setInterval(
      () => {
        const newProgress =this.state.progress+Math.random();
        if  (newProgress<99 ) {
          this.setState({progress: newProgress});
        }
      }, 2000);

    articleReview(this.state.title, this.state.articleContent, (adv)=>{
      this.setState({adviseEnglish: adv, isEnglishAdvice:true});
      if (NEED_TRANSLATION){
        advise2Chinese(adv, (ch)=>{
          // 转译中文
          this.setState({adviseChinese: ch});
          this.setState({advise: this.state.adviseChinese, isEnglishAdvice:false, progress: 101});
          clearInterval(counterInterval);
          const newRecords = this.state.records;
          newRecords.push({reviewTime: moment().format("YYYY-MM-DD HH:mm"), articleContent:this.state.articleContent, reviewEnglish:adv, reviewChinese: ch})
          this.setState({records:newRecords});
  
          this.saveHistoryArticleRecords();
        });
      } else {
        this.setState({advise: this.state.adviseEnglish, isEnglishAdvice:true, progress: 101});
        clearInterval(counterInterval);
        const newRecords = this.state.records;
        newRecords.push({reviewTime: moment().format("YYYY-MM-DD HH:mm"), articleContent:this.state.articleContent, reviewEnglish:adv, reviewChinese: ch})
        this.setState({records:newRecords});

        this.saveHistoryArticleRecords();
      }
    });

    ipcRenderer.send('record-historyArticleSubmit');

    Message({
      message: '已提交审批，请耐心等待',
      type: 'success'
    });

    setTimeout(()=>this.setState({submitLoading: false}), 2000);
  };

  translation = () => {
    if (this.state.isEnglishAdvice) {
      this.setState({advise: this.state.adviseChinese, isEnglishAdvice: !this.state.isEnglishAdvice});
    } else {
      this.setState({advise: this.state.adviseEnglish, isEnglishAdvice: !this.state.isEnglishAdvice});
    }
  };

  closeAdvise = () => {
    this.setState({advise: ''});
  };

  showHistory= () => {
    
  };

  readHistoryArticleRecords = () => {
    const filePath = 'articlehistory/'+this.state.title;
    ipcRenderer.send('read-local-file', filePath);

    ipcRenderer.once('read-local-file-reply',(event, data) => {
      const records = JSON.parse(data);
      this.setState({records:records});
    })
  }

  saveHistoryArticleRecords =  () => {
    const filePath = 'articlehistory/'+this.state.title;
    ipcRenderer.send('save-local-file', filePath, JSON.stringify( this.state.records));

    ipcRenderer.once('save-local-file-reply', function (event, data) {
      if (data===true) {
        Message({
          message: '批阅记录保存成功',
          type: 'success'
        });
      } else {
        Message({
          message: '批阅记录保存失败，前再次提交批阅',
          type: 'fail'
        });
      }
    })
  }

  render() {
    return (
      <div className={styles.demoContainer}>
        <Input type="textarea"  style={{height:'50px', 'margin-top': '5px'}} value={this.state.title} onChange={this.handleTitleChange} placeholder=""/>
        <Layout.Row gutter="20" style={{'margin-top': '5px'}}>
          <Layout.Col span="12">
            <div style={{'margin-left':'20px'}}>
              <Layout.Row gutter="20" style={{'margin-top':'5px'}}>
                <div>
                  <Input id='customArticleInput' type="textarea" value={this.state.articleContent} onChange={this.handleArticleChange} placeholder=""/>
                </div>
              </Layout.Row>
              <Layout.Row gutter="20" type="flex" align="middle" style={{'margin-top': '15px'}}>
                <Layout.Col>
                  <Button onClick={this.submitComposition} loading={this.state.submitLoading}>批阅</Button>
                </Layout.Col>
                <Layout.Col>
                  <HistoryRecords items={this.state.records}/>
                </Layout.Col>
              </Layout.Row>
            </div>
          </Layout.Col>

          <Layout.Col span="12">
            <Layout.Row gutter="20" type="flex" align="middle" style={{'margin-top':'5px'}}>
              <Input id='customAdviceInput' type="textarea" value={this.state.advise} />
            </Layout.Row>
            <Layout.Row gutter="20" type="flex" align="middle" style={{'margin-top': '15px'}}>
                <Layout.Col span="2">
                  {
                    this.state.progress!==0 &&
                      <div>
                        <Progress type="circle" width={32} percentage={this.state.progress.toFixed(2)} status={this.state.progress>=100?'success':''} />
                      </div>
                  }
                </Layout.Col>
                  <Layout.Col span="4">
                    <b>批改意见</b>
                  </Layout.Col>
                  <Layout.Col span="6">
                    <Button onClick={this.translation}>{this.state.isEnglishAdvice? <div>翻译为中文</div>: <div>切换至英文原话</div>}</Button>
                  </Layout.Col>
                  <Layout.Col span="4">
                    <Button onClick={this.closeAdvise}>清除</Button>
                  </Layout.Col>
            </Layout.Row>
          </Layout.Col>
        </Layout.Row>          
      </div>
    );
  }
}

export default CustomWriteBoard;